#!/bin/sh
###############################################################################
##  Author    : xuezhoyi
##  Name      : edw_kylin_builder.sh
##  Functions : build cube
##  Purpose   : build cube
##  Revisions or Comments
##  VER        DATE        AUTHOR           DESCRIPTION
##---------  ----------  ---------------  ------------------------------------ 
##  1.0      2017-05-22  xuezhouyi        1. CREATED THIS SHELL.
###############################################################################

. ${0%`basename ${0}`}edw_parm.sh
. ${0%`basename ${0}`}edw_func.sh

function USAGE(){
    echo -e "\nHow to use this shell script!"
    echo -e '\n${V_SHELL_HOME}/edw_kylin_builder.sh 20170101'
}

# Check variable
if [[ -z ${1} ]];then
    USAGE
    exit 1
fi

# Define basic parm
V_SCRIPT_NAME=$(basename ${0} | cut -d'.' -f1)
V_OUT_LOGS="${V_SHELL_LOGS}/${V_SCRIPT_NAME}_${1}_${V_TIME_STAMP}_$$.log"

# Define the output flow
exec 4>&1               # screen output
exec 3>>${V_OUT_LOGS}   # script output
exec 2>&3               # error output
exec 1>&3               # standard output
echo -e "[Begin: $(date +%F) $(date +%T)]"

# Define the variable
V_CURR_DATE=${1}
echo -e "\nCurrent date:${V_CURR_DATE}"
V_NEXT_DATE=$(GET_NEXT_DATE ${V_CURR_DATE})
echo -e "Next date:${V_NEXT_DATE}"
startDate=$(($(date -d "${V_CURR_DATE} 00:00:00" +%s)*1000))
echo -e "Start date:${startDate}."
endDate=$(($(date -d "${V_NEXT_DATE} 00:00:00" +%s)*1000))
echo -e "End date:${endDate}."
startTime=$((${startDate}+${V_KYLIN_MINUSTIME}))
echo -e "Start time:${startTime}."
endTime=$((${endDate}+${V_KYLIN_MINUSTIME}))
echo -e "End time:${endTime}."

# Get cube name
V_QUERY="SELECT CUBE_NAME FROM ETL.EDW_KYLIN_CONTROL WHERE IF_VALID = 'Y' AND FREQUENCY = 'D';"
V_CUBES=$(${V_RUN_MYSQL} -q "${V_QUERY}")
# Build cube
for CUBE in ${V_CUBES};do
    echo -e "\n[------------------------Start to build ${CUBE}------------------------]"
    curl -X PUT -H "Authorization: Basic QURNSU46S1lMSU4=" -H "Content-Type: application/json;charset=utf-8" -d '{"startTime": '${startTime}', "endTime": '${endTime}', "buildType": "BUILD"}' http://${V_KYLIN_LINK}:7070/kylin/api/cubes/${CUBE}/rebuild >> /dev/null
done

echo -e "\n[End: $(date +%F) $(date +%T)]"
echo 0 >&4
exit 0
